package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductSpecEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductTempSKUEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.UnitassistEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.ProductEntityMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.ProductMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.PageBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ProductService {
    private static final Logger logger = LoggerFactory.getLogger(ProductService.class);
    @Autowired
    private BaseService baseService;
    @Autowired
    private ProductEntityMapperImpl productEntityMapper;
    @Autowired
    private ProductMapperImpl productMapper;
    @Autowired
    private UnitService unitService;
    @Autowired
    private UnitassistService unitassistService;
    @Autowired
    private ProductSpecService productSpecService;
    @Autowired
    private ProductSKUTempService productSKUTempService;
    @Autowired
    private ManageClassService manageClassService;

    public ProductEntity SelectByIdXml(long Id) {
        return productEntityMapper.selectById(Id);
    }

    public Integer InsertEntityXml(ProductEntity entity) {
        return productEntityMapper.insert(entity);
    }

    public Integer UpdateEntityXml(ProductEntity entity) {
        return productEntityMapper.update(entity);
    }

    public ProductEntity SelectById(long Id) {
        return productMapper.selectById(Id);
    }

    public ProductEntity SelectByCode(String code, String tenantId) {
        return productMapper.selectByCode(code, tenantId);
    }

    public Boolean CheckEntity(long Id) {
        int rInt = productMapper.selectCount(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(ProductEntity entity) {
        return productMapper.insert(entity);
    }

    public Integer UpdateEntity(ProductEntity entity) {
        return productMapper.updateByPrimaryKey(entity);
    }

    public List<ProductEntity> SelectAll(String tenantId) {
        return productMapper.selectAll(tenantId);
    }

    public List<ProductEntity> SelectByIds(String tenantId, List<String> ids) {
        return productMapper.selectByIds(tenantId, ids);
    }

    public Integer DeleteById(Long Id) {
        return productMapper.deleteByPrimaryKey(Id);
    }

    public Integer InsertBatch(List<ProductEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = productMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    /**
     * 订阅事件同步数据
     *
     * @param content
     * @throws IOException
     */
    public void AutoDataEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String jsonString = obj.getArchive().replace("detail!productApplyRangeId", "detailproductApplyRangeId");
        jsonString = jsonString.replace("detail!id", "detailid").replace("detail!", "");

        ProductBean productBean = RequestTool.getBean(jsonString, ProductBean.class);
        String detailId = productBean.getId().toString();
        String productApplyRangeId = productBean.getProductApplyRange_OrgId();
        if (StringUtils.isEmpty(productApplyRangeId)) productApplyRangeId = productBean.getOrgId();
        String tenantId = content.getTenantId();
        if (StringUtils.isEmpty(tenantId)) tenantId = productBean.getYtenant();

        AutoDataEditNext(detailId, productApplyRangeId, tenantId);

    }
    private void AutoDataEditNext(String detailId, String productApplyRangeId, String tenantId) throws IOException {
        if (StringUtils.isEmpty(productApplyRangeId)) throw new IOException("OrgId 参数异常");
        Map<String, String> params = new HashMap<>();
        params.put("id", detailId);
        params.put("orgId", productApplyRangeId);
        AutoDataEditNext2(params, tenantId);
    }
    public void AutoDataEditNextByCode(String productCode, String productApplyRangeId, String tenantId) throws IOException {
        if (StringUtils.isEmpty(productApplyRangeId)) throw new IOException("OrgId 参数异常");
        Map<String, String> params = new HashMap<>();
        params.put("productCode", productCode);
        params.put("orgId", productApplyRangeId);
        AutoDataEditNext2(params, tenantId);
    }
    /**
     * 同步档案详情页数据
     * /yonbip/digitalModel/goodsproductskupro/list
     * @param tenantId
     * @throws IOException
     */
    private void AutoDataEditNext2(Map<String, String> params, String tenantId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return;
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();

        String requrl = gatewayUrl + ApiYon.getProDetail+"?access_token="+token;
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        GenericResponse<ProductMainBean> response = RequestTool.getBean(resString,
                new TypeReference<GenericResponse<ProductMainBean>>() {
                });
        if (response.getCode().equals("200")) {
            ProductMainBean productMainBean = response.getData();
            if (productMainBean.getId() > 0) {
                JSONObject myJSON = new JSONObject();

                JSONObject objJSON1 = JSONObject.parseObject(new Gson().toJson(productMainBean.getDetail()));
                productMainBean.setDetail(null);
                myJSON.putAll(objJSON1);

                JSONObject objJSON2 = JSONObject.parseObject(new Gson().toJson(productMainBean));
                myJSON.putAll(objJSON2);
                String objJSONStr = new Gson().toJson(myJSON);

                //主计量单位同步
                String unitId = String.valueOf(productMainBean.getUnit());
                int rInt = unitService.EventProductUnitEditById(tenantId, unitId);

                ProductBean productEntity = EventEditNew(objJSONStr, tenantId);

                //物料分类
                if (!StringUtils.isEmpty(productEntity.getManageClass())) {
                    manageClassService.EventManageClassEdit(productEntity.getManageClass(), tenantId);
                }
            }
        }
        else {
            throw new IOException(resString);
        }
    }

    /**
     * 同步档案、辅助计量
     * 预发标签检查更新物料档案、入库检查更新物料档案
     *
     * @param detailId
     * @param productApplyRangeId
     * @param tenantId
     * @throws IOException
     */
    public void AutoDataEditById(String detailId, String productApplyRangeId, String tenantId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return;
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String requrl = gatewayUrl + ApiYon.getProDetail + "?access_token=" + token;
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
//        params.put("access_token", token);
        params.put("id", detailId);
        params.put("orgId", productApplyRangeId);
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        GenericResponse<ProductMainBean> response = RequestTool.getBean(resString,
                new TypeReference<GenericResponse<ProductMainBean>>() {
                });
        if (response.getCode().equals("200")) {
            ProductMainBean productMainBean = response.getData();
            if (productMainBean.getId() > 0) {
                JSONObject myJSON = new JSONObject();

                JSONObject objJSON1 = JSONObject.parseObject(new Gson().toJson(productMainBean.getDetail()));
                productMainBean.setDetail(null);
                myJSON.putAll(objJSON1);

                JSONObject objJSON2 = JSONObject.parseObject(new Gson().toJson(productMainBean));
                myJSON.putAll(objJSON2);
                String objJSONStr = new Gson().toJson(myJSON);

                ProductBean productEntity = EventEditNew(objJSONStr, tenantId);
            }
        }
    }

    /**
     * 通过详情加载同步
     *
     * @param productEntity
     * @param tenantId
     * @throws IOException
     */
    public void EventEditExtend(ProductBean productEntity, String tenantId) throws IOException {
        if (productEntity != null && productEntity.getId() > 0) {
            String detailId = productEntity.getId().toString();
            String productApplyRangeId = productEntity.getProductApplyRangeId();
            //订阅物料档案 更新物料档案SKU表数据
            if (productEntity.getProductskus().size() > 0) {
                productSKUTempService.EventProductSKUTempEdit(productApplyRangeId, detailId, tenantId);
            }
            //模板使用情况加载单位数据 模板辅助计量单位
            if (!StringUtils.isEmpty(productEntity.getProductTemplate())) {
                unitassistService.EventProductUnitTempEdit(productApplyRangeId, productEntity.getProductTemplate(),
                        tenantId);
            }
            //物料分类
            if (!StringUtils.isEmpty(productEntity.getManageClass())) {
                manageClassService.EventManageClassEdit(productEntity.getManageClass(), tenantId);
            }
        }
    }

    /**
     * 20240803之前版本
     * @param jsonString
     * @param tenantId
     * @return
     * @throws IOException
     */
    private ProductBean EventEdit(String jsonString, String tenantId) throws IOException {
        ProductBean productBean = RequestTool.getBean(jsonString, ProductBean.class);
        productBean.setTenantId(tenantId);
        String jsonStr = new Gson().toJson(productBean);
        ProductEntity productEntity = RequestTool.getBean(jsonStr, ProductEntity.class);
        TimeBean time = productEntity.getTime();
        if (time!=null) {
            productEntity.setProductApplyRangeId(time.getProductApplyRangeId());
        }
        productEntity.setRemark_dxq(jsonString);
        //辅助计量单位 物料详情数据
        if (productBean.getEnableAssistUnit() || productBean.getProductAssistUnitExchanges().size() > 0) {
            List<UnitassistEntity> listUnitAssist = productBean.getProductAssistUnitExchanges();
            listUnitAssist.forEach(item -> {
                item.setProductTemplate(productBean.getProductTemplate());
                item.setTenant_id(tenantId);
            });
            int rInt = unitassistService.InsertBatch(listUnitAssist);
            System.out.println("[listUnitAssist]" + rInt);
        }
        //物料规格 物料详情数据
        if (productBean.getProductspecitems() != null && productBean.getProductspecitems().size() > 0) {
            List<ProductSpecEntity> listProductSpec = productBean.getProductspecitems();
            listProductSpec.forEach(item -> {
                item.setProductTemplate(productBean.getProductTemplate());
                item.setTenant_id(tenantId);
            });
            int rInt = productSpecService.InsertBatch(listProductSpec);
            System.out.println("[ProductSpec]" + rInt);
        }
        //物料SKUtemp 物料详情数据
        if (productBean.getProductskus() != null && productBean.getProductskus().size() > 0) {
            List<ProductTempSKUBean> listProductSKUTemp = productBean.getProductskus();
            List<ProductTempSKUEntity> myList = new ArrayList<>();
            listProductSKUTemp.forEach(item -> {
                ProductTempSKUEntity obj = new ProductTempSKUEntity();
                obj = MyTool.convertBean2Bean(item, ProductTempSKUEntity.class);
                obj.setSkuName(item.getName());
                obj.setMyModel(item.getModel());
                obj.setMyModelDescription(item.getModelDescription());
                obj.setTenant_id(tenantId);
                myList.add(obj);
            });
            int rInt = productSKUTempService.InsertBatch(myList);
            System.out.println("[ProductSKUTemp]" + rInt);
        }

        //检测是否存在，不存在新增，存在更新；
        Boolean flag = CheckEntity(productEntity.getId());
        if (flag) {
            int rInt = UpdateEntity(productEntity);
            if (rInt > 0) return productBean;
        } else {
            int rInt = InsertEntity(productEntity);
            if (rInt > 0) return productBean;
        }
        return null;
    }
    private ProductBean EventEditNew(String jsonString, String tenantId) throws IOException {
        ProductBean productBean = RequestTool.getBean(jsonString, ProductBean.class);
        productBean.setTenantId(tenantId);
        String jsonStr = new Gson().toJson(productBean);
        ProductEntity productEntity = RequestTool.getBean(jsonStr, ProductEntity.class);
        productEntity.setRemark_dxq(jsonString);
        //辅助计量单位 物料详情数据
        if (productBean.getEnableAssistUnit() || productBean.getProductAssistUnitExchanges().size() > 0) {
            List<UnitassistEntity> listUnitAssist = productBean.getProductAssistUnitExchanges();
            listUnitAssist.forEach(item -> {
                item.setProductTemplate(productBean.getProductTemplate());
                item.setTenant_id(tenantId);
            });
            int rInt = unitassistService.InsertBatch(listUnitAssist);
            System.out.println("[listUnitAssist]" + rInt);
        }
        //物料规格 物料详情数据
        if (productBean.getProductspecitems() != null && productBean.getProductspecitems().size() > 0) {
            List<ProductSpecEntity> listProductSpec = productBean.getProductspecitems();
            listProductSpec.forEach(item -> {
                item.setProductTemplate(productBean.getProductTemplate());
                item.setTenant_id(tenantId);
            });
            int rInt = productSpecService.InsertBatch(listProductSpec);
            System.out.println("[ProductSpec]" + rInt);
        }
        //物料SKUtemp 物料详情数据
        if (productBean.getProductskus() != null && productBean.getProductskus().size() > 0) {
            List<ProductTempSKUBean> listProductSKUTemp = productBean.getProductskus();
            List<ProductTempSKUEntity> myList = new ArrayList<>();
            listProductSKUTemp.forEach(item -> {
                ProductTempSKUEntity obj = new ProductTempSKUEntity();
                obj = MyTool.convertBean2Bean(item, ProductTempSKUEntity.class);
                obj.setSkuName(item.getName());
                obj.setMyModel(item.getModel());
                obj.setMyModelDescription(item.getModelDescription());
                obj.setTenant_id(tenantId);
                myList.add(obj);
            });
            int rInt = productSKUTempService.InsertBatch(myList);
            System.out.println("[ProductSKUTemp]" + rInt);
        }

        //检测是否存在，不存在新增，存在更新；
        Boolean flag = CheckEntity(productEntity.getId());
        if (flag) {
            int rInt = UpdateEntity(productEntity);
            if (rInt > 0) return productBean;
        } else {
            int rInt = InsertEntity(productEntity);
            if (rInt > 0) return productBean;
        }
        return null;
    }
    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        Long Id = Long.parseLong(obj.getId());
        Boolean flag = CheckEntity(Id);
        if (flag) {
            int rInt = DeleteById(Id);
            return rInt;
        }
        return 0;
    }

    //yonbip/digitalModel/product/batch
    //主动物料批量加载
    public int EventProductEdit(String tenantId, List<String> ids) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String requrl = gatewayUrl + ApiYon.getProBatch + "?access_token=" + token;
        Map<String, Object> paramsObj = new HashMap<>();
        paramsObj.put("id", ids);
        Map<String, Object> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("data", paramsObj);
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        GenericResponse<List<ProductBeanSimple2>> response = RequestTool.getBean(resString,
                new TypeReference<GenericResponse<List<ProductBeanSimple2>>>() {
                });
        int recordCount = 0;
        if (response.getCode().equals("200")) {
            List<ProductBeanSimple2> resData = response.getData();
            for (ProductBeanSimple2 productMainBean : resData) {
                if (productMainBean.getId() > 0) {
                    String detailId = String.valueOf(productMainBean.getId());
                    AutoDataEditNext(detailId, productMainBean.getProductApplyRange_OrgId(), tenantId);
                    recordCount++;
                }
            }
        }

        return recordCount;
    }

    /**
     * 初始化 主动物料批量加载 仅批量同步物料档案
     * 不同步辅助计量单位
     * @param tenantId
     * @return
     * @throws IOException
     */
    public int EventProductEdit(String tenantId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        int curPageIndex = 0;
        boolean flagNext = true;
        while (flagNext) {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            String requrl = gatewayUrl + ApiYon.getProList2 + "?access_token=" + token;
            Map<String, String> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("pageIndex", String.valueOf(curPageIndex + 1));
            params.put("pageSize", "499");
            String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
            GenericResponse<PageBean<ProductMainBean2>> response = RequestTool.getBean(resString,
                    new TypeReference<GenericResponse<PageBean<ProductMainBean2>>>() {
                    });
            if (!response.getCode().equals("200")) {
                throw new RuntimeException(resString);
            }
            // 业务处理
            curPageIndex = response.getData().getPageIndex();
            int endPageIndex = response.getData().getEndPageIndex();

            List<ProductMainBean2> resData = response.getData().getRecordList();
            if (resData == null || resData.size() == 0) {
                flagNext = false;
                break;
            }
            recordCount += resData.size();

            resData.forEach(item -> {
                try {
                    AutoDataEditNextByCode(item.getCode(), item.getCreateOrgId(), tenantId);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

            if (endPageIndex <= curPageIndex) flagNext = false;
        }
        return recordCount;
    }

    /**
     * 20240803之前备份
     * @param tenantId
     * @return
     * @throws IOException
     */
    public int EventProductEditOld(String tenantId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        int curPageIndex = 0;
        boolean flagNext = true;
        while (flagNext) {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            String requrl = gatewayUrl + ApiYon.getProList + "?access_token=" + token;
            Map<String, String> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("pageIndex", String.valueOf(curPageIndex + 1));
            params.put("pageSize", "499");
            String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
            GenericResponse<PageBean<ProductMainBean>> response = RequestTool.getBean(resString,
                    new TypeReference<GenericResponse<PageBean<ProductMainBean>>>() {
                    });
            if (!response.getCode().equals("200")) {
                throw new RuntimeException(resString);
            }
            // 业务处理
            curPageIndex = response.getData().getPageIndex();
            int endPageIndex = response.getData().getEndPageIndex();

            List<ProductMainBean> resData = response.getData().getRecordList();
            if (resData == null || resData.size() == 0) {
                flagNext = false;
                break;
            }
            recordCount += resData.size();

            List<ProductEntity> myData = new ArrayList<>();
            resData.forEach(item -> {
                ProductMainBean productMainBean = item;
                try {
                    if (productMainBean.getId() > 0) {
                        JSONObject myJSON = new JSONObject();
                        JSONObject objJSON1 = JSONObject.parseObject(new Gson().toJson(productMainBean.getDetail()));
                        productMainBean.setDetail(null);
                        myJSON.putAll(objJSON1);
                        JSONObject objJSON2 = JSONObject.parseObject(new Gson().toJson(productMainBean));
                        myJSON.putAll(objJSON2);
                        String objJSONStr = new Gson().toJson(myJSON);
                        ProductEntity productEntity = null;
                        productEntity = RequestTool.getBean(objJSONStr, ProductEntity.class);
                        productEntity.setTenantId(tenantId);
                        productEntity.setRemark_dxq(objJSONStr);
                        myData.add(productEntity);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            });
            int rIntNew = InsertBatch(myData);
            recordCount += rIntNew;

            if (endPageIndex <= curPageIndex) flagNext = false;
        }
        return recordCount;
    }



}
